<?php
/**
 * 数据字典管理
 * @author huangjian E-mail:870596179@qq.com
 * @version 创建时间：2016年4月12日 上午10:26:16 
 * 类说明
 */
class TypeAction extends BaseAction{
	/**
	 * @authority 浏览
	 */
	public function index(){
		$this->display();
	}
	
	//列表
	public function getAllData(){
		$Model = M($this->getActionName());
		$map = $this->loadSeachCondition();
		$map['flag'] = 1;
		$total = $Model->where($map)->count();// 查询满足要求的总记录数
		$page = json_decode($this->pageParam($total));
		$data = $Model->where($map)->limit($page->firstRow,$page->listRows)->order($page->sort)->select();
		$vo = $this->toJosnForGird($data,$page);
		echo json_encode($vo);
	}
	
	/**
	 * 组装条件
	 * @return multitype:multitype:string
	 */
	public function loadSeachCondition(){
		$map = array();
		/*
		if(!empty($_GET['field'])){
			$map['field'] = array("like","%".$_GET['field']."%");
		}
		*/
		return $map;
	}
	
	/**
	 * @authority 查看小类
	 */
	public function getSubTypeAllData(){
		$Model = M('Subtype');
		$map = $this->loadSeachCondition();
		$map['flag'] = 1;
		$map['parent_id'] = $_GET['id'];
		$total = $Model->where($map)->count();// 查询满足要求的总记录数
		$page = json_decode($this->pageParam($total));
		$data = $Model->where($map)->limit($page->firstRow,$page->listRows)->order($page->sort)->select();
		$vo = $this->toJosnForGird($data,$page);
		echo json_encode($vo);
	}
	
	/**
	 * 插入大类
	 */
	public function insert(){
		$Model = M($this->getActionName());
		unset ( $_POST [$Model->getPk()] );
		if (false === $Model->create()) {
			$this->error($Model->getError());
		}
		$data = $Model->create();
		if($data['reserve'] == 1){
			//查询最大排序
			$map['reserve'] = 1;
			$max_seq = $Model->where($map)->order('seq desc')->getField('seq');
			$data['seq'] = $max_seq + 1;
		}
		//保存当前数据对象
		if ($result = $Model->add($data)) { //保存成功
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_ADD_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_ADD_ERROR'),0);
		}
	}
	
	/**
	 * @authority 修改大类
	 */
	public function edit() {
		$Model = M($this->getActionName());
		$map['id'] = $_REQUEST['id'];
		$vo = $Model->where($map)->find();
		$this->assign('vo',$vo);
		$this->display();
	}
	
	/**
	 * 更新大类
	 */
	public function update() {
		$Model = D($this->getActionName());
		if(false === $Model->create()) {
			$this->error($Model->getError());
		}
		// 更新数据
		if(false !== $Model->save()) {
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
		}
	}
	
	/**
	 * @authority 修改大类排序
	 */
	public function editMainSeq() {
		$Model = M('Type');
		$TypeModel = M('Type');
		$map['flag'] = 1;
		$map['reserve'] = 1;
		$data = $Model->where($map)->order('seq asc')->field('id,type_name as name')->select();
		$newData = array();
		$newData[0]['id'] = -1;
		$newData[0]['pId'] = 0;
		$newData[0]['name'] = "菜单";
		$newData[0]['isParent'] = true;
		$newData[0]['open'] = true;
		for($i=0; $i<count($data); $i++) {
			$newData[$i+1]['id'] = $data[$i]['id'];
			$newData[$i+1]['pId'] = $newData[0]['id'];
			$newData[$i+1]['name'] = $data[$i]['name'];
		}
		$this->assign("zNodes",json_encode($newData));
		$this->display();
	}
	
	/**
	 * @authority 更新大类排序
	 */
	public function updateMainSeq(){
		$Model = M('Type');
		//批量更新
		$seq = $_REQUEST['seq'];
		$sql .= 'SET seq = CASE id ';
		foreach ($seq as $key=>$val){
			$ids .= $val.",";
			$key++;
			$sql .= ' WHEN '.$val.' THEN '.$key." ";
		}
		$sql .= ' END ';
		$ids = substr($ids,0,strlen($ids)-1);
		$sql .= 'where id in ('.$ids.')';
		$where['id'] = array('in',$ids);
		$data['_query'] = $sql;
		$result = $Model->execute('update __TABLE__ '.$sql);
		if($result !== false){
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_SEQ_SUCCESS'),1);
		}else{
			$this->ajaxReturn(0,L('ADMIN_SEQ_ERROR'),0);
		}
	}
	
	
	
	/**
	 * @authority 新增小类
	 */
	public function addSubType(){
		$id = $_REQUEST['id'];
		$this->assign('parent_id',$id);
		$this->display();
	}
	
	/**
	 * @authority 插入小类
	 */
	public function insertSubType(){
		$Model = M('Subtype');
		unset ( $_POST [$Model->getPk()] );
		if (false === $Model->create()) {
			$this->error($Model->getError());
		}
		$data = $Model->create();
		//查询最大排序
		$map['flag'] = 1;
		$map['parent_id'] = $data['parent_id'];
		$max_seq = $Model->where($map)->order('seq desc')->getField('seq');
		$data['seq'] = $max_seq + 1;
		//保存当前数据对象
		if ($result = $Model->add($data)) { //保存成功
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_ADD_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_ADD_ERROR'),0);
		}
	}
	
	/**
	 * @authority 修改小类
	 */
	public function editSubType() {
		$Model = M('Subtype');
		$map['id'] = $_REQUEST['id'];
		$vo = $Model->where($map)->find();
		$this->assign('vo',$vo);
		$this->display();
	}
	
	/**
	 * @authority 更新小类
	 */
	public function updateSubType() {
		$Model = M('Subtype');
		if(false === $Model->create()) {
			$this->error($Model->getError());
		}
		// 更新数据
		if(false !== $Model->save()) {
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_EDIT_SUCCESS'),1);
		} else {
			$this->ajaxReturn(0,L('ADMIN_EDIT_ERROR'),0);
		}
	}
	
	/**
	 * @authority 修改小类排序
	 */
	public function editSeq() {
		$Model = M('Subtype');
		$TypeModel = M('Type');
		$map['flag'] = 1;
		$map['parent_id'] = $_GET['id'];
		$typeVo = $TypeModel->where("id=".$_GET['id']." and flag = 1")->find();
		$data = $Model->where($map)->order('seq asc')->field('id,subtype_name as name')->select();
		$newData = array();
		$newData[0]['id'] = -1;
		$newData[0]['pId'] = 0;
		$newData[0]['name'] = $typeVo['type_name'];
		$newData[0]['isParent'] = true;
		$newData[0]['open'] = true;
		for($i=0; $i<count($data); $i++) {
			$newData[$i+1]['id'] = $data[$i]['id'];
			$newData[$i+1]['pId'] = $newData[0]['id'];
			$newData[$i+1]['name'] = $data[$i]['name'];
		}
		$this->assign("zNodes",json_encode($newData));
		$this->display();
	}
	
	/**
	 * @authority 更新小类排序
	 */
	public function updateSeq(){
		$Model = M('Subtype');
		//批量更新
		$seq = $_REQUEST['seq'];
		$sql .= 'SET seq = CASE id ';
		foreach ($seq as $key=>$val){
			$ids .= $val.",";
			$key++;
			$sql .= ' WHEN '.$val.' THEN '.$key." ";
		}
		$sql .= ' END ';
		$ids = substr($ids,0,strlen($ids)-1);
		$sql .= 'where id in ('.$ids.')';
		$where['id'] = array('in',$ids);
		$data['_query'] = $sql;
		$result = $Model->execute('update __TABLE__ '.$sql);
		if($result !== false){
			$this->deleteSession();
			$this->ajaxReturn(1,L('ADMIN_SEQ_SUCCESS'),1);
		}else{
			$this->ajaxReturn(0,L('ADMIN_SEQ_ERROR'),0);
		}
	}
	
	/**
	 * 删除大类
	 */
	public function delType(){
		$Model = M($this->getActionName());$ProductModel = M("Product");
		if (!empty($Model)) {
			$pk = $Model->getPk();
			$id = $_REQUEST[$pk];
			if (isset($id)) {
				$map['flag'] = 1;
				$map['type_id'] = $id;
				$count = $ProductModel->where($map)->count();
				if($count > 0){
					$this->ajaxReturn(0,"该类型已被商品绑定，请删除或解绑后操作！",0);
				}
				$condition = array($pk => array('in', explode(',', $id)));
				if (false !== $Model->where($condition)->setField('flag',2)) {
					$this->deleteSession();
					$this->ajaxReturn(1,L('ADMIN_DELETE_SUCCESS'),1);
				} else {
					$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
				}
			} else {
				$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
			}
		}
	}
	
	/**
	 * 删除小类
	 */
	public function delSubType(){
		$Model = M("Subtype");$ProductModel = M("Product");
		if (!empty($Model)) {
			$pk = $Model->getPk();
			$id = $_REQUEST[$pk];
			if (isset($id)) {
				$subtype_code = $Model->where("id=".$id)->getField("subtype_code");
				if (empty($subtype_code)) {$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);}
				$map['flag'] = 1;
				$map['subtype_code'] = $subtype_code;
				$count = $ProductModel->where($map)->count();
				if($count > 0){
					$this->ajaxReturn(0,"该类型已被商品绑定，请删除或解绑后操作！",0);
				}
				$condition = array($pk => array('in', explode(',', $id)));
				if (false !== $Model->where($condition)->setField('flag',2)) {
					$this->deleteSession();
					$this->ajaxReturn(1,L('ADMIN_DELETE_SUCCESS'),1);
				} else {
					$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
				}
			} else {
				$this->ajaxReturn(0,L('ADMIN_DELETE_ERROR'),0);
			}
		}
	}
	
	
	//检查大类别是否可用
	public function checkType(){
		$param = $_REQUEST['param'];
		$Model = M($this->getActionName());
		$where['type_name'] = $param;
		$where['flag'] = 1;
		$count = $Model->where($where)->count();
		if($count){
			echo '该类别已被使用！';
		}else{
			echo 'y';
		}
	}
	//检查大类别是否可用，排除本数据
	public function exCheckType(){
		$param = $_REQUEST['param'];
		$Model = M($this->getActionName());
		if(!empty($_REQUEST['id'])){
			$map['id'] = $_REQUEST['id'];
			$result = $Model->where($map)->find();
			if($param == $result['type_name']) {
				echo 'y';
				return;
			}else{
				$where['type_name'] = $param;
			}
		}else{
			$where['type_name'] = $param;
		}
		$where['flag'] = 1;
		$count = $Model->where($where)->count();
		if($count){
			echo '该类别已被使用！';
		}else{
			echo 'y';
		}
	}
	
	
	//检查小类别是否可用
	public function checkSubType(){
		$param = $_REQUEST['param'];
		$Model = M('Subtype');
		$where['subtype_name'] = $param;
		$where['flag'] = 1;
		$count = $Model->where($where)->count();
		if($count){
			echo '该类别已被使用！';
		}else{
			echo 'y';
		}
	}
	//检查小类别是否可用，排除本数据
	public function exCheckSubType(){
		$param = $_REQUEST['param'];
		$Model = M('Subtype');
		if(!empty($_REQUEST['id'])){
			$map['id'] = $_REQUEST['id'];
			$result = $Model->where($map)->find();
			if($param == $result['subtype_name']) {
				echo 'y';
				return;
			}else{
				$where['subtype_name'] = $param;
			}
		}else{
			$where['subtype_name'] = $param;
		}
		$where['flag'] = 1;
		$count = $Model->where($where)->count();
		if($count){
			echo '该类别已被使用！';
		}else{
			echo 'y';
		}
	}
	
	
	//检查小类编号是否可用
	public function checkSubTypeCode(){
		$param = $_REQUEST['param'];
		$Model = M('Subtype');
		$where['subtype_code'] = $param;
		$where['flag'] = 1;
		$count = $Model->where($where)->count();
		if($count){
			echo '该类别编号已被使用！';
		}else{
			echo 'y';
		}
	}
	//检查小类编号是否可用，排除本数据
	public function exCheckSubTypeCode(){
		$param = $_REQUEST['param'];
		$Model = M('Subtype');
		if(!empty($_REQUEST['id'])){
			$map['id'] = $_REQUEST['id'];
			$result = $Model->where($map)->find();
			if($param == $result['subtype_code']) {
				echo 'y';
				return;
			}else{
				$where['subtype_code'] = $param;
			}
		}else{
			$where['subtype_code'] = $param;
		}
		$where['flag'] = 1;
		$count = $Model->where($where)->count();
		if($count){
			echo '该类别编号已被使用！';
		}else{
			echo 'y';
		}
	}
	
	//图片传图
	public function uploadImg(){
		$folderName = $_POST['folderName'];//格式  首字母大写
		$prefix = $_POST['prefix'];//格式  m_,s_
		$maxWidth = $_POST['maxWidth'];//格式500,200
		$maxHeight = $_POST['maxHeight'];//格式500,200
		import('ORG.Net.UploadFile');
		$targetFolder_b = './Uploads/'.$folderName.'/'.date('Y-m-d').'/';
		if(!is_dir($targetFolder_b)){
			@mkdir($targetFolder_b,0777);
		}
		$upload = new UploadFile();// 实例化上传类
		$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath =  $targetFolder_b;// 设置附件上传目录
		if($maxWidth != 0 && $maxHeight != 0){
			$upload->thumb = true;
			$upload->thumbPrefix = $prefix;  //缩略图前缀
			$upload->thumbMaxWidth = $maxWidth;
			$upload->thumbMaxHeight = $maxHeight;
			$upload->thumbType = 0;//按设置大小截取 0 按原图等比例缩略
			$upload->thumbRemoveOrigin = true; //上传后移除原图
		}
		if(!$upload->upload()) {// 上传错误提示错误信息
			$this->ajaxReturn(0,$upload->getErrorMsg(),0);
		}else{// 上传成功
			$info =  $upload->getUploadFileInfo();
			//补上缩略图的前缀
			if($maxWidth != 0 && $maxHeight != 0){
				$bak['url'] = ltrim($info[0]['savepath'],".").$prefix.$info[0]['savename'];
			}else{
				$bak['url'] = ltrim($info[0]['savepath'],".").$info[0]['savename'];
			}
			$bak['localname'] = $info[0]['name'];
			$this->ajaxReturn($bak,'上传成功！',1);
		}
	}
	
	private function deleteSession(){
		//版本号
		if(!S('S_PRODUCT_VERSION')){
			S('S_PRODUCT_VERSION',10000);
		}else{
			S('S_PRODUCT_VERSION',S('S_PRODUCT_VERSION')+1);
		}
		S('S_PRODUCT',null);
	}
}